package cn.juque.common.abstracts;

import cn.hutool.core.text.CharSequenceUtil;
import cn.juque.common.constants.MessageEnum;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author nuoka
 * @version 1.0.0
 * <li>xxl-job调度基类</li>
 * @date 2022/7/14 14:31
 **/
@Slf4j
public abstract class AbstractXxlJobHandler {

    /**
     * 开始执行
     */
    public void start() {
        Long jobId = XxlJobHelper.getJobId();
        String format = "jobId={}, message:{}, costs={}ms";
        try {
            long start = System.currentTimeMillis();
            String message = this.run();
            long end = System.currentTimeMillis();
            message = CharSequenceUtil.isNotEmpty(message) ? message : MessageEnum.OK.getMsg();
            String logStr = CharSequenceUtil.format(format, jobId, message, end - start);
            XxlJobHelper.handleSuccess(logStr);
        } catch (Exception e) {
            log.error("xxl-job error, jobId={}", jobId, e);
            XxlJobHelper.handleFail(e.getMessage());
        }
    }

    /**
     * 业务具体实现
     * @return 消息描述
     */
    protected abstract String run() ;
}
